﻿using System;
using Microsoft.VisualStudio.SharePoint;
using EnvDTE;
using System.Collections.Generic;

namespace CodeCounsel.SharePoint.DevTools.ItemTypes
{
    class FullTrustProxyRefactoring
    {
        internal static void StartListening(ISharePointProjectItemTypeDefinition typeDefinition)
        {
            typeDefinition.FileAdded += new EventHandler<SharePointProjectItemFileEventArgs>(TypeDefinition_FileAdded);

        }

        static void TypeDefinition_FileAdded(object sender, SharePointProjectItemFileEventArgs e)
        {
            ISharePointProjectItemFile file = e.ProjectItemFile;
            if (file.DeploymentType == DeploymentType.NoDeployment)
            {
                ProjectItem dteItem = file.ProjectItem.Project.ProjectService.Convert<ISharePointProjectItemFile, ProjectItem>(file);
                if (dteItem.Kind == "Compile" && dteItem.FileCodeModel != null)
                {
                    foreach(EnvDTE.CodeClass codeClass in FindClasses(dteItem.FileCodeModel))
                    {
                        if (IsOperationClass(codeClass))
                        {

                        }
                    }
                }
            }
        }

        private static IEnumerable<CodeClass> FindClasses(FileCodeModel fileCodeModel)
        {
            return FindClassesRecursive(fileCodeModel.CodeElements);
        }

        private static IEnumerable<CodeClass> FindClassesRecursive(CodeElements codeElements)
        {
            foreach (CodeElement element in codeElements)
            {
                if (element is CodeClass)
                {
                    yield return (CodeClass)element;
                }
                else if (element is CodeNamespace)
                {
                    CodeNamespace codeNamespace = (CodeNamespace)element;
                    foreach(CodeClass codeClass in FindClassesRecursive(codeNamespace.Children))
                    {
                        yield return codeClass;
                    }
                }
            }
        }

        private static bool IsOperationClass(CodeClass codeClass)
        {
            return codeClass.get_IsDerivedFrom("SPProxyOperation");
        }
    }
}
